package com.yc.demohoudun.web;

import com.yc.demohoudun.entiy.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class IndexAction {

    @Value("${upload.diskPath}")
    String diskPath;

    @Value("${upload.webPath}")
    String webPath;

    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable String name) {
        return  "Hello " + name;
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String prefix= UUID.randomUUID().toString().replaceAll("-","");
        int index=filename.lastIndexOf(".");
        String suffix =index==-1?"":filename.substring(index);
        String newFileName = prefix+suffix;
        File fileObj=new File(diskPath,newFileName);
        file.transferTo(fileObj);
        String webFilePath="http://127.0.0.1:8888"+webPath+"/"+newFileName;
        return new Result(1,"文件上传成功",webFilePath);
    }
}
